var NestableGoodsCats = function () {
    var updateOutput = function (e) {
        var list = e.length ? e : $(e.target),
            output = list.data('output');
        if (window.JSON) {
            output.val(window.JSON.stringify(list.nestable('serialize'))); //, null, 2));
			$.post(ajaxUrl,{data:list.nestable('serialize'),ajax:'catSort'},function(data){				
			});
			//alert(output.val());
        } else {
            output.val('JSON browser support required for this demo.');
        }
    };
	
	var showall =function(list, parent) {
		for (var menu in list) {
			var id =list[menu].root.catId;
			
			if(list[menu].root.priceSection){
				var priceSection = ' | '+list[menu].root.priceSection;
			}else{
				var priceSection = '';
			}
			
			var name = list[menu].root.catName+priceSection;
			if(list[menu].root.catFlag==1){
				var catFlag = '<a href="" class="catFlag btn btn-xs blue">显示</a>';
			}else{
				var catFlag = '<a href="" class="catFlag btn btn-xs default">隐藏</a>';
			}
			var li = $("<li class='dd-item' data-id='"+id+"'></li>")
			var ac= '<div class="pull-right" style="position:absolute;top:4px;right:4px">'+catFlag+' <a class="new btn btn-xs green" href=""><i class="fa fa-plus"></i> 添加子分类</a> <a class="edit btn btn-xs default" href=""><i class="fa fa-edit"></i> 修改</a> <a class="delete btn btn-xs red" href=""><i class="fa fa-trash-o"></i> 删除</a></div>';
			$(li).append("<div class='dd-handle' >"+name+"</div>"+ac).appendTo(parent);
			if(list[menu].children!=undefined){
				var ol = $("<ol class='dd-list'></ol>");
				$(ol).appendTo($(li));
				showall(list[menu].children,$(ol));			
			}
		}
	}
	
	
    return {
        //main function to initiate the module
        init: function () {
			$.post(ajaxUrl,'',function(data){
				var menulist = data;
				//var menulist = [{"id":1},{"id":2,"children":[{"id":3},{"id":4}]},{"id":5,"children":[{"id":6},{"id":7}]},{"id":8},{"id":9}];
				var showlist = $(" <ol class=\"dd-list\"></ol>");
				showall(menulist, showlist);
				$("#nestable").append(showlist);
				// activate Nestable for list 1
				$('#nestable').nestable({
					//group: 1
				})
					.on('change', updateOutput);


				// output initial serialised data
				$('.dd').nestable('collapseAll');
				updateOutput($('#nestable').data('output', $('#nestable_output')));
				
				$('#nestable_list_menu').on('click', function (e) {
					var target = $(e.target),
						action = target.data('action');
					if (action === 'expand-all') {
						$('.dd').nestable('expandAll');
					}
					if (action === 'collapse-all') {
						$('.dd').nestable('collapseAll');
					}
				});
			
			});
			
						
			//显示状态
			$('#nestable a.catFlag').live('click', function (e) {
                e.preventDefault();
				var edit =$(this);
				var catId = edit.parents('li').eq(0).attr('data-id');
				var catFlag = edit.html()=='显示'?0:1;
				$.post(ajaxUrl,{catId:catId,catFlag:catFlag,ajax:'catFlag'},function(data){
					if(data){
						layer.msg('分类状态修改成功！',{icon: 1,time: 2000});
						if(catFlag==0){
							edit.after('<a href="" class="catFlag btn btn-xs default">隐藏</a>').remove();
						}else{
							edit.after('<a href="" class="catFlag btn btn-xs blue">显示</a>').remove();
						}
					}else{
						layer.msg('分类状态未修改！',{icon: 2,time: 2000});
						return;
					}
			   });
            });
			
			//删除
            $('#nestable a.delete').live('click', function (e) {
                e.preventDefault();
				var edit =$(this);
				var catId = edit.parents('li').eq(0).attr('data-id');
				layer.confirm('确定删除该分类？',function(index){
					$.post(ajaxUrl,{catId:catId,ajax:'delGoodsCats'},function(data){
						if(data==="other"){
							layer.msg('该分类存在子类不能删除！',{icon: 2,time: 2000});
							return;
						}
						if(data){
							layer.msg('分类删除成功！',{icon: 1,time: 2000});
							edit.parents('li').eq(0).remove();
						}else{
							layer.msg('分类删除失败！',{icon: 2,time: 2000});
							return;
						}
				   });					
				});
            });
			
			//保存
			$('#responsive button[type="submit"]').live('click', function (e) {
                e.preventDefault();
				$.ajax({
					url:ajaxUrl,
					type : "post",  
					dataType : "json",  
					data: $(".form-horizontal").serialize(),  
					success : function(data) {
						if(data.status=='1'){
							layer.msg(data.info, 
								{icon: 1,time: 2000},
								function(){
									$('#responsive').modal('hide');
									location.reload();
								}
							);   	
						}else{
							layer.msg(data.info, 
								{icon: 2,time: 2000}
							);   
							return;
						}
					}  
				});    
			});

            $('#nestable a.edit').live('click', function (e) {
                e.preventDefault();
				$('.modal-header h4')[0].innerHTML = '修改分类';//表头修改
				
				var edit =$(this);
				var editing = edit.parents('li').eq(0);
				var catId = editing.attr('data-id');
				var parentId = editing.parents('li').eq(0).attr('data-id');
				parentId = parentId?parentId:0;
				var name = editing.children('.dd-handle').html();
				var catName = name.split('|')[0];
				var priceSection=name.split('|')[1]?name.split('|')[1]:'';
				$('#responsive input[name="ajax"]').val('editGoodsCats');
				//赋值
				$('#responsive input[name="catId"]').eq(0).val(catId);
				$('#responsive input[name="catName"]').eq(0).val(catName);
				$('#responsive input[name="priceSection"]').eq(0).val(priceSection);
								
				//selected
				var jqOpts = $('option');
				for (var i = 0, iLen = jqOpts.length; i < iLen; i++) {
					//先清空
					jqOpts.eq(i).attr('selected',false);					
					if(parentId==jqOpts.eq(i).val()){
						jqOpts.eq(i).attr('selected',true);						
					}
				} 
				
				//打开模态框
				$('#responsive').modal('show');
            });
			
			//添加
            $('#table_common_new').click(function (e) {				
				$('.modal-header h4')[0].innerHTML = '添加新分类';				
				var jqName = $('#responsive input[name="catName"]').eq(0);
				jqName.val('');//清空分类名
				
				var jqRole = $('#responsive input[name="catId"]').eq(0);
				jqRole.val('');//清空ID
				
				$('#responsive input').val(""); 
				$('#responsive input[name="ajax"]').val('addGoodsCats');
				//select
				$('option').attr('selected',false);
				$('#responsive').modal('show');//显示模态框 
				
            });
			
			$('#nestable a.new').live('click', function (e) {
                e.preventDefault();
				$('.modal-header h4')[0].innerHTML = '添加子分类';
				var parentId = $(this).parents('li').eq(0).attr('data-id');
				var jqName = $('#responsive input[name="catName"]').eq(0);
				jqName.val('');//清空分类名
				
				var jqRole = $('#responsive input[name="catId"]').eq(0);
				jqRole.val('');//清空ID
				
				$('#responsive input').val(""); 
				$('#responsive input[name="ajax"]').val('addGoodsCats');
				
				//selected
			
				
				
				//parentId = parentId?parentId:0;
				
				var jqOpts = $('option');
				for (var i = 0, iLen = jqOpts.length; i < iLen; i++) {
					//先清空
					jqOpts.eq(i).attr('selected',false);					
					if(parentId==jqOpts.eq(i).val()){
						jqOpts.eq(i).attr('selected',true);						
					}
				} 
				
				//$('option').attr('selected',false);
				$('#responsive').modal('show');//显示模态框
			});
        }

    };

}();